﻿using System;
using System.Security.Claims;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;

namespace TokenDemo.Web.Services
{
    public class HttpContextCurrent
    {
        /// <summary>
        /// 只能获取AddTransient和AddSingleton注入的对象
        /// </summary>
        public static IServiceProvider Instance { get; set; }
        /// <summary>
        /// 用户不存在返回空的对象
        /// </summary>
        /// <returns></returns>
        public static UserIdentity GetCurrentUser()
        { 
            UserIdentity userIdentity = new UserIdentity();
            try
            {
                var http = Instance.GetRequiredService<IHttpContextAccessor>();
                if (http.HttpContext.User.Identity.IsAuthenticated)
                {
                    if (http.HttpContext.User.Identity is ClaimsIdentity identity)
                    {
                        var claims = identity.Claims;
                        userIdentity.Id = identity.FindFirst("UserId")?.Value;
                        userIdentity.Name = identity.FindFirst("Name")?.Value;
                    }
                }
                else
                {
                    // 没有授权也尝试获取当前用户信息
                    if (http.HttpContext.User.Identity is ClaimsIdentity identity)
                    {
                        var claims = identity.Claims;
                        userIdentity.Id = identity.FindFirst("UserId")?.Value;
                        userIdentity.Name = identity.FindFirst("Name")?.Value;
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
            return userIdentity;

        }
       

    }
}